<template>
  <div class="flex h-full">
    <a-card v-if="showType === '1'" class="mr-2 py-2 h-full" :body-style="{ height: '100%', padding: '0 8px', display: 'flex', flexDirection: 'column' }">
      <SearchComb v-model:value="searchCombData" class="w-56" placeholder="姓名/助记码/卡号/手机号/身份证号" @search="getList()" />
      <BaseList :data-source="listDataSource" :loading="loading" class="flex-1 overflow-auto">
        <template #renderItem="{ item }">
          <div class="py-2 px-3" :class="patientId === item?.jzbh ? 'active' : ''" @click="onSelectPatient(item)">
            <div class="flex justify-between">
              <div class="text-base font-bold text-primary truncate w-16" :title="item.brName">{{ item.brName }}</div>
              <div style="color: #52c41a">已发药</div>
            </div>
            <div class="flex justify-between pt-2">
              <div class="text-grey">{{ formatDate(item.ghsj, 'YYYY-MM-DD HH:mm') }}</div>
              <div class="w-20 text-grey text-right">{{ item.rysx }}</div>
            </div>
          </div>
        </template>
      </BaseList>
      <a-form>
        <SelectDrugRoom v-model:value="drugStoreId" :params="{ isProducer: '1' }" placeholder="选择药房" class="w-full mb-2" @select="onSelectDrugRoom" />
        <a-form-item class="w-full" label="">
          <a-select v-model:value="reviewer" :options="pharmacistSelectData" placeholder="选择审核人" />
        </a-form-item>
      </a-form>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <!-- <PatientTabs v-if="showType === '2'" class="mb-2 pb-2"> -->
      <ReadCard v-if="showType === '3'" business-type="门诊退药" :call-back-data="readCallData" @read="onReadCard" @tab-change="onReset" />
      <SearchContainer v-if="showType !== '1'" search-text="刷新" @search="getTableData" @reset="onReset">
        <div class="flex justify-between">
          <a-form ref="formRef" class="form-style-flex" :model="searchData" :label-col="{ style: { width: '80px' } }">
            <a-form-item label="" name="brName" class="w-72">
              <SelectTable
                v-model:value="searchData.brName"
                :search-params="{ stdate: searchData['dateRange']?.[0], eddate: searchData['dateRange']?.[1], lb: 1, drugStoreId, fflb: '0' }"
                type="门诊退药患者列表"
                :disabled="!drugStoreId"
                placeholder="姓名/助记码/卡号/手机号/身份证号"
                @select="onSelectPatient"
              />
            </a-form-item>
            <a-form-item :label="isArmy ? '发药日期' : '收费日期'" name="dateRange">
              <a-range-picker v-model:value="searchData['dateRange']" class="w-64" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :allow-clear="false" />
            </a-form-item>
          </a-form>
          <a-form class="flex">
            <SelectDrugRoom
              v-model:value="drugStoreId"
              :params="{ isProducer: '1' }"
              placeholder="选择药房"
              class="w-64 mb-2 mr-4"
              @select="onSelectDrugRoom"
            />
            <a-form-item class="w-64" label="审核人">
              <a-select v-model:value="reviewer" :options="pharmacistSelectData" placeholder="请选择" />
            </a-form-item>
          </a-form>
        </div>
      </SearchContainer>
      <PatientInfoHeader :patient-info="patientInfo" :show-insurance="true" @change="onChangeInfo">
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue class="ml-2" label="卡号" :width="160" :value="patientInfo.brId" />
            <LabelValue class="ml-2" label="病案号" :value="patientInfo[isBGMSG ? 'brBlkh' : 'oprSn']" :width="160" />
            <LabelValue class="ml-2" label="科室" :width="140" :value="patientInfo.ksmc" />
            <LabelValue class="ml-2" label="类别" :width="140" :value="patientInfo.ghlb" />
            <!-- <LabelValue class="ml-4" label="过敏史" :width="280" :tooltip="true" :value="patientInfo.brGms" /> -->
            <AllergyHistory class="ml-2" :width="280" :value="patientInfo.brGms" :patient-info="patientInfo" @success="(e) => (patientInfo.brGms = e)" />
          </div>
          <div class="flex items-center">
            <LabelValue class="ml-2" label="门诊号" :width="160" :value="patientInfo.jzbh" />
            <LabelValue class="ml-2" label="病历号" :value="patientInfo[isBGMSG ? 'oprSn' : 'brBlkh']" :width="160" />
            <LabelValue class="ml-2" label="医生" :width="140" :value="patientInfo.empName" />
            <LabelValue class="ml-2" label="时间" :width="140" :value="patientInfo.ghsj" />
            <LabelValue class="ml-2" label="初步诊断" :width="320" :value="patientInfo?.zdmc" />
          </div>
        </div>
      </PatientInfoHeader>
      <a-card class="mt-2 w-full flex-1 overflow-auto overflow-x-hidden">
        <template v-if="tableData.length">
          <template v-for="(tableItem, tableIndex) in tableData" :key="tableItem.cfbh">
            <BaseTable :loading="tableLoading" column-code="00001028" class="mb-2" :data-source="tableItem.children">
              <template #title>
                <div class="flex justify-between items-center">
                  <div class="flex">
                    <div class="font-bold mr-2">处方{{ tableIndex + 1 }}:{{ tableItem.cfbh }}</div>
                    <div class="ml-4">{{ tableItem.children[0].drugStoreName }}</div>
                  </div>
                  <a-button type="primary" ghost> 打印处方单 </a-button>
                </div>
              </template>
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'action'">
                  <!-- <BaseButton confirm-text="是否确认此计划单?" danger type="link" size="small" :disabled="record.jhzt === 1" @click="onReturn(record)">
                  退药
                </BaseButton> -->

                  <a-button type="link" danger size="small" @click="onReturn(record)"> 退药 </a-button>
                </template>
                <template v-if="column.dataIndex === 'mc'">
                  <MedicineInfo :value="{ mc: record.mc, gg: record.gg, cj: record.cj }" />
                </template>
                <template v-if="column.dataIndex === 'fyff'"> {{ record.fyff }} </template>
                <template v-if="column.dataIndex === 'pl'"> {{ record.pl }} </template>
                <template v-if="column.dataIndex === 'zxdwsl'"> {{ record.jlsl }} {{ record.jldw }} </template>
                <template v-if="column.dataIndex === 'cfts'"> {{ record.cfts || 0 }}天 </template>
                <template v-if="column.dataIndex === 'sl'"> {{ record.sl }}{{ record.dw }} </template>
                <template v-if="column.dataIndex === 'type'">
                  {{ record.tcid ? '套餐' : '单项' }}
                </template>
              </template>
            </BaseTable>
          </template>
        </template>
        <a-empty v-else class="mt-10" />
      </a-card>
    </div>
    <a-modal v-model:open="open" title="退药" centered :width="600" ok-text="保存" :confirm-loading="confirmLoading" @ok="onSave">
      <div class="flex justify-between items-center">
        <div class="w-[80%] yaop">{{ formatSate.mc }} / {{ formatSate.gg }} / {{ formatSate.cj }}</div>
        <div>
          <span>发药数量：</span><span>{{ formatSate.sl }}{{ formatSate.dw }}</span>
        </div>
      </div>
      <a-divider class="!my-4" />
      <a-form ref="formRef" class="form-style-flex" :model="formatSate" :label-col="{ style: { width: '80px' } }">
        <a-form-item label="退药数量" class="w-1/2">
          <a-input v-model:value="formatSate.tysl" v-input:int placeholder="请输入">
            <template #suffix>
              <span class="text-slate-400">{{ formatSate.dw }}</span>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item v-if="showType === '3'" label="" class="w-1/2 pl-2">
          <div class="flex items-center">
            <a-input
              v-model:value="scInput"
              placeholder="请扫追溯码"
              maxlength="20"
              class="w-[85%]"
              :disabled="!formatSate.tysl || scDataSource.length === Number(formatSate.tysl)"
              @keydown.enter="onCodeEnter"
            />
            <div class="text-center flex-1">
              <a-popover title="">
                <template #content>
                  <div>
                    <BaseTable class="w-[300px]" :columns="scColumns" :data-source="scDataSource">
                      <template #bodyCell="{ column, index, record }">
                        <template v-if="column.dataIndex === 'xh'">
                          {{ index + 1 }}
                        </template>
                        <template v-if="column.dataIndex === 'action'">
                          <a-button type="link" danger size="small" @click="onDelSc(record)"> 删除 </a-button>
                        </template>
                      </template>
                    </BaseTable>
                  </div>
                </template>
                <span class="text-red-500"> {{ scDataSource.length || 0 }}/{{ formatSate.tysl || 0 }} </span>
              </a-popover>
            </div>
          </div>
        </a-form-item>
        <a-form-item label="备注" class="w-full">
          <a-textarea v-model:value="formatSate.remark" :rows="4" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>
    <SelectBillModal v-model:open="openSelectModal" :resource-data="allBillData" @ok="onSelectBill" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import { post } from '@/utils/request'
import BaseList from '@/components/BaseList'
import BaseTable from '@/components/BaseTable'
import SearchComb from '@/components/SearchComb'
import { formatDate } from '@/utils/format'
import { getSystemConfig } from '@/utils/systemConfig'
import useUserStore from '@/store/user'
import cofirmModal from '@/utils/confirm.js'
import SelectBillModal from './SelectBillModal.vue'

//获取患者信息
const { empId } = useUserStore()
const tableData = ref([])
const listDataSource = ref([])
const formatSate = ref({})
const formRef = ref(null)
const searchData = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const searchCombData = ref({})
const loading = ref(false)
const confirmLoading = ref(false)
const tableLoading = ref(false)

const open = ref(false)
const patientId = ref('') //就诊编号
const patientInfo = ref({})
// const patientInfo = usePatient(patientId, '门诊')
const pharmacistSelectData = ref([])
const reviewer = ref(undefined) //审核人
const drugStoreId = ref(undefined) //发药药房
const isArmy = ref(false) //是否为jun用
const showType = ref('1')
const openSelectModal = ref(false)
const allBillData = ref({})
const tabActiveKey = ref('自费')
const readCallData = ref({})

//获取门诊患者信息
const getOutpatientInfo = async () => {
  const { data, code } = await post('/outp/mzys/getOutpRecordInfo', { mzjlbh: patientId.value })
  if (code === 0) {
    patientInfo.value = data
    searchData.value.brName = data.brName
  }
}

const onChangeInfo = () => {
  if (showType.value === '1') {
    getList()
  } else if (showType.value === '2') {
    // getOutpatientInfo()
    onReset()
  }
}
const getData = async () => {
  if (!patientId.value) return message.error('请选择患者')
  tableLoading.value = true
  const { code, data } = await post('/outp/mzyf/getOutpClinicalOrderInfoList', {
    jzbh: patientId.value,
    drugStoreId: drugStoreId.value,
    status: '2',
    tclb: '0',
    sfyzfyz: 1
  })
  tableLoading.value = false
  if (code !== 0) return
  tableData.value = data
}

const getTableData = () => {
  patientId.value && getData()
}

const onReset = (e) => {
  patientId.value = ''
  formRef.value?.resetFields()
  tableData.value = []
  listDataSource.value = []
  patientInfo.value = {}
  searchData.value.brName = ''
  tabActiveKey.value = e
}

const onReturn = async (item) => {
  scDataSource.value = []
  if (!reviewer.value) {
    message.error('请选择审核人')
    return
  }
  if (item.tcid) {
    const isConfirm = await cofirmModal({ title: '提示', content: '当前药品属于套餐药品，只可退药整个套餐，确认退药？' })
    if (isConfirm) {
      // open.value = true
      formatSate.value.tysl = item.sl
      formatSate.value.id = item.id
      formatSate.value.remark = ''
      await onSave(2)
    }
  } else {
    open.value = true
    formatSate.value = item
    formatSate.value.remark = ''
  }
}
const onSave = async (state = 1) => {
  if (state === 1) {
    if (formatSate.value.tysl == null || formatSate.value.tysl === '') {
      message.error('退药数量不可为空')
      return
    }
    if (formatSate.value.tysl === 0 || formatSate.value.tysl === '0') {
      message.error('退药数量不可为0')
      return
    }
    if (formatSate.value.tysl > formatSate.value.sl) {
      message.error('退药数量不可大于原始数量')
      return
    }
  }
  if (!reviewer.value) {
    message.error('请选择审核人')
    return
  }
  const reviewerValue = JSON.parse(window.localStorage.getItem('returnReviewer'))
  if (reviewerValue && reviewerValue.time && reviewerValue.value) {
    if (reviewerValue.value !== reviewer.value) {
      setLocalStorageEvent()
    }
  } else {
    setLocalStorageEvent()
  }
  confirmLoading.value = true
  const res = await post('/outp/mzyf/doRefundDrugNew', {
    tysl: formatSate.value.tysl,
    remark: formatSate.value.remark,
    yzbh: formatSate.value.id,
    tyshr: reviewer.value
  })
  if (res.code !== 0) {
    message.error(res.msg || '操作失败')
    confirmLoading.value = false
  } else {
    scDataSource.value.length && onSaveSc()
    message.success(res.msg)
    open.value = false
    confirmLoading.value = false
    if (showType.value === '1') {
      getList()
    } else {
      await getData()
      if (tableData.value.length === 0) {
        formatSate.value = {}
        patientInfo.value = {}
        searchData.value.brName = ''
      }
    }
  }
}
//获取审核人下拉（类别为药剂师）
const getSelectPharmacist = async () => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    emplbid: '5',
    yxzt: 0,
    pageNum: 1,
    pageSize: 9999
  })
  if (code !== 0) return
  pharmacistSelectData.value = data.map((item) => {
    return {
      label: item.empName,
      value: item.empId
    }
  })
  const reviewerValue = JSON.parse(window.localStorage.getItem('returnReviewer'))
  if (reviewerValue && reviewerValue.time && reviewerValue.value) {
    //保存24小时
    if (dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') >= 0 && dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') < 24) {
      reviewer.value = reviewerValue.value
    }
  }
}
const setLocalStorageEvent = () => {
  window.localStorage.setItem(
    'returnReviewer',
    JSON.stringify({
      time: dayjs().format(),
      value: reviewer.value
    })
  )
}
//左侧数据
const getList = async (params = {}) => {
  const drugStoreIdValue = JSON.parse(window.localStorage.getItem('dispensingDrugStoreId'))
  if (drugStoreIdValue && drugStoreIdValue.value) {
    drugStoreId.value = drugStoreIdValue.value
  }
  if (!drugStoreId.value) return
  listDataSource.value = []
  loading.value = true
  const { data } = await post('/outp/mzyf/getOutpRecordListByClinicalOrderMZTY', {
    pyjm: searchCombData.value.searchKey,
    eddate: searchCombData.value.endDate,
    stdate: searchCombData.value.startDate,
    drugStoreId: drugStoreId.value,
    xmlbs: [2, 4, 5],
    lb: 1,
    fflb: '0',
    ...params
  })
  loading.value = false
  listDataSource.value = data || []
  if (data.length > 0) {
    if (data.length > 1 && tabActiveKey.value !== '自费') {
      allBillData.value = data
      openSelectModal.value = true
    } else {
      onSelectBill(listDataSource.value[0])
    }
  } else {
    params.brId && message.error('没有数据')
    patientId.value = ''
    tableData.value = []
  }
  // data.length && getOutpatientInfo()
  // data.length && getData()
}
const onSelectBill = (select) => {
  patientId.value = select.jzbh
  readCallData.value.medTypeName = select?.medTypeName
  readCallData.value.insutypeName = select?.insutypeName
  getOutpatientInfo()
  getData()
}
const onSelectDrugRoom = (val) => {
  drugStoreId.value = val.id
  window.localStorage.setItem(
    'dispensingDrugStoreId',
    JSON.stringify({
      value: drugStoreId.value
    })
  )
  onReset()
  showType.value === '1' && getList()
}

const onSelectPatient = (item) => {
  patientId.value = item.jzbh
  searchData.value.brName = item.brName
  getOutpatientInfo()
  getData()
}
const getDepartInfo = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId: empId })
  if (res.code !== 0) message.error(res.msg || '获取失败')
  drugStoreId.value = res.data?.defaultStoreId
}

onMounted(() => {
  getSelectPharmacist()
  const drugStoreIdValue = JSON.parse(window.localStorage.getItem('dispensingDrugStoreId'))
  if (drugStoreIdValue && drugStoreIdValue.value) {
    drugStoreId.value = drugStoreIdValue.value
  } else {
    getDepartInfo()
  }
  showType.value = getSystemConfig('OUTDISPENSINSG_STYLE') || '1' //门诊退药界面样式
  window.history.pushState(null, null, window.location.href + '?type=' + showType.value)
  isArmy.value = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
})
const scDataSource = ref([])
const scColumns = [
  { title: '序号', dataIndex: 'xh' },
  { title: '追溯码', dataIndex: 'zsm' },
  { title: '操作', dataIndex: 'action' }
]
const scInput = ref('')
const onCodeEnter = async () => {
  if (!scInput.value) return message.error('请扫码')
  const { data, msg, code } = await post('/outp/outpTraceCode/doScanRefundTraceCodeRecord', {
    mzyzbID: formatSate.value.id,
    tcCode: scInput.value
  })
  if (code === 0) {
    if (scDataSource.value.find((item) => item.zsm === scInput.value)) {
      return message.error('追溯码重复')
    }
    message.success('扫码成功')
    scDataSource.value.push({ ...data, zsm: scInput.value })
    scInput.value = ''
  } else {
    message.error(msg || '失败')
    scInput.value = ''
  }
}
const onSaveSc = async () => {
  const { msg, code } = await post('/outp/outpTraceCode/doSaveOutpRefundTcRecordList', {
    mzyzbID: formatSate.value.id,
    tcCodeList: scDataSource.value.map((item) => item.zsm)
  })
  if (code !== 0) return message.error(msg || '失败')
}
const onDelSc = (row) => {
  scDataSource.value = scDataSource.value.filter((item) => item.zsm !== row.zsm)
}

const onReadCard = async (info) => {
  const brId = info.ybkResonse?.br_id
  if (brId) {
    getList({ brId, stdate: searchData.value['dateRange']?.[0], eddate: searchData.value['dateRange']?.[1] })
  } else {
    message.error('没有数据')
  }
}
</script>
